package com.dingding.order.core.cancel.biz.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dto.AbstractResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.UserTaxiOrdert;
import com.dingding.common.core.beans.Userorder;
import com.dingding.common.core.model.push.PushModel;
import com.dingding.common.core.push.pushmsg.PushData;
import com.dingding.common.core.push.pushmsg.PushMsg;
import com.dingding.common.core.sms.model.MessageModel;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.facade.queue.dto.msg.MessageRequestsDTO;
import com.dingding.facade.queue.dto.push.PushRequestDTO;
import com.dingding.facade.queue.enums.ClientType;
import com.dingding.facade.queue.enums.PushType;
import com.dingding.facade.queue.enums.RoleType;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.order.code.CancelOrderCodeMsg;
import com.dingding.order.code.order.OrderStatus;
import com.dingding.order.code.order.TaxiOrderStatus;
import com.dingding.order.core.cancel.biz.ICancelOrderService;
import com.dingding.order.core.cancel.dao.ICancelUserOrderDao;
import com.dingding.order.core.cancel.dao.ITaxiCancelOrderTDao;
import com.dingding.order.dto.cancel.PushAutoCancelTaxiOrderDTO;
import com.dingding.order.dto.cancel.PushTaxiCancelOrderDTO;
import com.dingding.order.dto.cancel.ReqTaxiCancelOrderDTO;
import com.dingding.order.dto.cancel.ResTaxiCancelOrderDTO;

/**
 * 
 * @ClassName: TaxiCancelOrderServiceImpl 
 * @Description: 出租车取消订单业务逻辑实现类 
 * @author YHQ
 * @date 2016年6月29日 下午2:42:38
 * 
 */
@Component("taxiCancelOrderService")
public class TaxiCancelOrderServiceImpl extends AbstractResponse<ResTaxiCancelOrderDTO, ReqTaxiCancelOrderDTO> implements ICancelOrderService {

	private Logger log = Logger.getLogger(this.getClass());
 	
	@Resource(name="taxiCancelOrderTDao")
	private ITaxiCancelOrderTDao taxiCancelOrderTDao;
	
	@Resource(name="cancelUserOrderDao")
	private ICancelUserOrderDao cancelUserOrderDao;

	@Resource(name = "queueService")
	private IQueueFacade queuefacade;
	
	/**
	 * 
	 * @Title: taxiCancelOrder 
	 * @Description: 出租车取消订单
	 * @param reqTaxiCancelOrderDTO 出租车取消订单客户端请求Bean
	 * @author YHQ 
	 * @return String    返回类型
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public String cancelOrder(String requestData) {
		
		// 客户端响应信息
		ResponseEntity<ResTaxiCancelOrderDTO> response = new ResponseEntity<ResTaxiCancelOrderDTO>();
		
		// 客户端请求参数
		ReqTaxiCancelOrderDTO cancelOrderDTO = super.parseRequestJson(requestData);
		
		// 验证客户端请求参数
		if(!super.validateParam(response, cancelOrderDTO)){
			return super.responseBeanToJson(response);
		}
		
		// 获取待取消订单信息(下面操作均会用到)
		UserTaxiOrdert taxiOrdert = taxiCancelOrderTDao.getUserOrder(cancelOrderDTO.getOid());
		
		// 是否符合取消订单条件
		if(!cancelOrderCondition(taxiOrdert, response)){
			return super.responseBeanToJson(response);
		}
		
		// 取消订单操作
		if(!cancelOrderOperation(taxiOrdert, cancelOrderDTO)){
			
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(CancelOrderCodeMsg.CANCEL_ORDER_ERROR);
			response.setPromptMessage(CancelOrderCodeMsg.CANCEL_ORDER_ERROR);
			
			return super.responseBeanToJson(response);
		}
		
		// 取消订单，通知对方(发送短信、推送消息)
		this.cancelOrderNotice(taxiOrdert, cancelOrderDTO);
		
		//取消出租车订单成功，返回成功响应码
		response.setCode(HttpStatus.SC_OK);
		
		return super.responseBeanToJson(response);
	}

	/**
	 * 
	 * @Title: cancelOrderCondition 
	 * @Description: 取消订单条件
	 * @author YHQ 
	 * @return boolean    true:符合条件   false:不符合条件
	 * @version V2.3.0
	 * 
	 */
	public boolean cancelOrderCondition(UserTaxiOrdert taxiOrdert,ResponseEntity<ResTaxiCancelOrderDTO> response){
		
		// 订单不存在，返回相应的响应码和消息
		if(taxiOrdert == null){
			
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(CancelOrderCodeMsg.ORDER_NOT_EXISTS);
			response.setPromptMessage(CancelOrderCodeMsg.ORDER_NOT_EXISTS);
			return false;
		}
		
		// 订单状态不是待支付状态，返回相应的响应码和消息
		if(taxiOrdert.getOrderStatus() == 3){
			
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(CancelOrderCodeMsg.ORDER_STATUS_ERROR);
			response.setPromptMessage(CancelOrderCodeMsg.ORDER_STATUS_ERROR);
			return false;
		}
		
		return true;
	}
	
	/**
	 * 
	 * @Title: cancelOrderOperation 
	 * @Description: 取消出租车订单操作
	 * @param taxiOrdert 待取消出租车订单信息
	 * @param taxiCancelOrderDTO 取消订单客户端请求参数
	 * @author YHQ 
	 * @return void    返回类型
	 * 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public boolean cancelOrderOperation(UserTaxiOrdert taxiOrdert,ReqTaxiCancelOrderDTO taxiCancelOrderDTO){
		
		Userorder userOrder = getUserorder(taxiOrdert, taxiCancelOrderDTO);
		
		try {
			
			// 保存订单信息到正式表
			cancelUserOrderDao.save(userOrder);
			
			// 删除临时出租车订单信息
			taxiCancelOrderTDao.delete(taxiOrdert);
			
		} catch (Exception e) {
			log.error("取消出租车订单操作时出现异常   类："+this.getClass()+" cancelOrderOperation()", e);
			return false;
		}
		
		return true;
	}
	
	/**
	 * 
	 * @Title: cancelOrderNotice 
	 * @Description: 取消订单通知 
	 * @param taxiOrdert 出租车订单信息
	 * @param taxiCancelOrderDTO 取消出租车订单客户端请求参数
	 * @author YHQ 
	 * @return void    返回类型
	 * 
	 */
	public void cancelOrderNotice(UserTaxiOrdert taxiOrdert,ReqTaxiCancelOrderDTO taxiCancelOrderDTO){
		
		// 订单状态为待抢单时，无任何推送
		if(taxiOrdert.getOrderStatus() != 1){
			
			// 要推送的用户Id
			String pushUserId = null;
			// 取消人
			String cancelUserId = taxiCancelOrderDTO.getUserId();
			
			if(taxiCancelOrderDTO.getCancelType() == 1){
				pushUserId = taxiOrdert.getGrabOrderUserId();
				cancelUserId = taxiOrdert.getPlaceOrderUserId();
			}else{
				pushUserId = taxiOrdert.getPlaceOrderUserId();
				cancelUserId = taxiOrdert.getGrabOrderUserId();
			}
			
			// 获取取消订单推送信息
			PushTaxiCancelOrderDTO pushTaxiCancelOrderDTO = taxiCancelOrderTDao.getPushTaxiCancelOrderInfo(cancelUserId, pushUserId,taxiCancelOrderDTO.getCancelType());
			
			//取消原因
			pushTaxiCancelOrderDTO.setCancelDesc(taxiCancelOrderDTO.getCancelDesc());
			//发布订单类型
			pushTaxiCancelOrderDTO.setPublishType(2);
			// 订单类型
			pushTaxiCancelOrderDTO.setOrderStatus(5);
			
			// 发送短信
			this.sendMessage(pushTaxiCancelOrderDTO);
			
			// 推送消息
			this.pushMessage(pushTaxiCancelOrderDTO, taxiOrdert, taxiCancelOrderDTO);
			
			// 通知推送消息
			this.pushNoticeMessage(pushTaxiCancelOrderDTO, taxiOrdert, taxiCancelOrderDTO);
		}
	}
	
	/**
	 * 
	 * 取消订单发送短信
	 * 
	 * @Title: sendMessage 
	 * @param pushCancelOrderDTO 
	 * @author YHQ
	 * 
	 */
	public void sendMessage(PushTaxiCancelOrderDTO pushTaxiCancelOrderDTO){

		MessageRequestsDTO messageRequestsDTO = new MessageRequestsDTO();
		messageRequestsDTO.setTelPhone(pushTaxiCancelOrderDTO.getTellPhone());
		messageRequestsDTO.setMessageContent(
				MessageModel.cancelOrder(pushTaxiCancelOrderDTO.getPassengerName(), pushTaxiCancelOrderDTO.getCancelDesc(),2));
		queuefacade.addMessageToQueue(JSONUtil.toJSONString(messageRequestsDTO));

	}

	/**
	 *  取消订单推送消息
	 * 
	 * @Title: pushMessage 
	 * @param pushCancelOrderDTO    设定文件 
	 * @author YHQ
	 * 
	 */
	public void pushMessage(PushTaxiCancelOrderDTO pushTaxiCancelOrderDTO, UserTaxiOrdert taxiOrdert,
			ReqTaxiCancelOrderDTO reqTaxiCancelOrderDTO) {

		// 推送Bean
		PushData pushData = new PushData();

		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular("cancelOrderPush");

		// 推送内容
		pushData.setResponseBody(pushTaxiCancelOrderDTO);

		PushRequestDTO pushRequestDTO = new PushRequestDTO();
		pushRequestDTO.setAlert(PushMsg.CANCEL_ORDER);
		pushRequestDTO.setAliasId(pushTaxiCancelOrderDTO.getDriverId());
		pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));
		pushRequestDTO.setPushType(PushType.alert_msgcontent);
		
		//乘客取消
		if(reqTaxiCancelOrderDTO.getCancelType() == 1){
			pushRequestDTO.setRoleType(RoleType.Driver);
			
		//车主取消
		}else{
			pushRequestDTO.setRoleType(RoleType.Passenger);
		}
		
		
		// 设备类型
		if (pushTaxiCancelOrderDTO.getLoginEquipment().equals("Android")) {
			pushRequestDTO.setClientType(ClientType.Android);
		} else if (pushTaxiCancelOrderDTO.getLoginEquipment().equals("iOS")) {
			pushRequestDTO.setClientType(ClientType.iOS);
		}

		queuefacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));

	}
	
	/**
	 *  取消订单 - 推送通知消息
	 * 
	 * @Title: pushNoticeMessage 
	 * @param pushCancelOrderDTO    设定文件 
	 * @author YHQ
	 * 
	 */
	public void pushNoticeMessage(PushTaxiCancelOrderDTO pushTaxiCancelOrderDTO, UserTaxiOrdert taxiOrdert,
			ReqTaxiCancelOrderDTO reqTaxiCancelOrderDTO) {
		
		// 推送Bean
		PushData pushData = new PushData();
		
		String content = MessageModel.cancelOrder(pushTaxiCancelOrderDTO.getPassengerName(), pushTaxiCancelOrderDTO.getCancelDesc(),2);
		
		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular("newsNoticePush");
		
		// 推送内容
		pushData.setResponseBody(PushModel.noticeModel(1, content, null));
		
		PushRequestDTO pushRequestDTO = new PushRequestDTO();
		
		// 别名
		pushRequestDTO.setAliasId(pushTaxiCancelOrderDTO.getDriverId());
		// 推送内容
		pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));
		// 推送类型
		pushRequestDTO.setPushType(PushType.msgcontent);
		// 设备类型
		if (pushTaxiCancelOrderDTO.getLoginEquipment().equals("Android")) {
			pushRequestDTO.setClientType(ClientType.Android);
		} else if (pushTaxiCancelOrderDTO.getLoginEquipment().equals("iOS")) {
			pushRequestDTO.setClientType(ClientType.iOS);
		}
		
		queuefacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));
		
	}
	
	/**
	 * @Title: getUserorder
	 * @Description: 将taxiOrdert中的数据赋值给UserOrder
	 * @param taxiOrdert 订单临时表对象中的数据
	 * @author YHQ
	 * @since V2.3.0
	 * @return UserOrder 订单正式表对象
	 * @throws
	 */
	public Userorder getUserorder(UserTaxiOrdert taxiOrdert,ReqTaxiCancelOrderDTO taxiCancelOrderDTO) {

		// 创建userOrder对象
		Userorder userOrder = new Userorder();
		// 主键Id
		userOrder.setOid(taxiOrdert.getTaxiOrdertId());
		// 下单用户Id
		userOrder.setPlaceOrderUserId(taxiOrdert.getPlaceOrderUserId());
		// 下单城市
		userOrder.setPayCity(taxiOrdert.getPlaceOrderCity());
		// 出发时间
		userOrder.setSetOutTime(taxiOrdert.getSetOutTime());
		// 出发地址
		userOrder.setStartAddress(taxiOrdert.getStartAddress());
		// 起点经度
		userOrder.setStartLongitude(taxiOrdert.getStartLongitude());
		// 起点纬度
		userOrder.setStartLatitude(taxiOrdert.getStartLatitude());
		// 目的地
		userOrder.setEndAddress(taxiOrdert.getEndAddress());
		// 目的地经度
		userOrder.setEndLongitude(taxiOrdert.getEndLongitude());
		// 目的地纬度
		userOrder.setEndLatitude(taxiOrdert.getEndLatitude());
		// 距离
		userOrder.setDistance(taxiOrdert.getDistance());
		// 叮币支付金额
		userOrder.setPayMoney(taxiOrdert.getPayMoney());
		// 支付宝支付金额
		userOrder.setAlipayMoney(taxiOrdert.getAlipayMoney());
		// 总金额
		userOrder.setTotalMoney(taxiOrdert.getTotalMoney());
		// 人数
		userOrder.setNumber(taxiOrdert.getNumber());
		// 留言
		userOrder.setMessage(taxiOrdert.getMessage());
		// 距对方距离
		userOrder.setPayDistance(taxiOrdert.getPayDistance());
		// 抢单用户Id
		userOrder.setGrabOrderUserId(taxiOrdert.getGrabOrderUserId());
		// 抢单时间
		userOrder.setGrabOrderTime(taxiOrdert.getGrabOrderTime());
		// 订单状态
		userOrder.setOrderStatus(OrderStatus.ORDER_STATUS_CANCEL);
		// 下单时间
		userOrder.setCreateTime(taxiOrdert.getCreateTime());
		// 订单支付时间
		userOrder.setPayTime(taxiOrdert.getPayTime());
		// 乘客确认到达时间
		userOrder.setEndTime(taxiOrdert.getEndTime());
		// 取消订单时间
		userOrder.setCancelTime(new Date());
		// 下单用户类型
		userOrder.setOrderType(taxiOrdert.getOrderType());
		//下单类型 出租车订单
		userOrder.setPublishType(2);
		
		if(taxiCancelOrderDTO !=null){
			
			// 取消类型
			userOrder.setCancelType(taxiCancelOrderDTO.getCancelType());
			// 订单取消原因
			userOrder.setCancelDesc(taxiCancelOrderDTO.getCancelDesc());
			//取消订单编号
			userOrder.setCancelNumber(1);
			//出租车订单取消人
			userOrder.setCancelUserId(taxiCancelOrderDTO.getUserId());
		}else{
			
			// 取消类型
			userOrder.setCancelType(2);
			// 订单取消原因
			userOrder.setCancelDesc("订单超市，自动取消");
		}
		// 支付类型
		userOrder.setPayType(taxiOrdert.getPayType());

		return userOrder;
	}

	
	/** 
	 * 
	 * @Title: autoCancelOrder 
	 * @Description: 出租车自动取消订单
	 * @author YHQ
	 * @return void
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public void autoCancelOrder() {
		
		// 获取待自动取消订单
		List<UserTaxiOrdert> taxiOrderts = taxiCancelOrderTDao.geTaxiOrderts();
		
		// 取消订单操作
		if(taxiOrderts != null && taxiOrderts.size() > 0){
			
			for (int i = 0; i < taxiOrderts.size(); i++) {
				
				UserTaxiOrdert taxiOrdert = taxiOrderts.get(i);
				
				//取消订单操作
				boolean flag = cancelOrderOperation(taxiOrdert, null);
				
				// 取消订单操作成功，通知用户(发送短信，推送消息)
				if(flag){
					
					PushAutoCancelTaxiOrderDTO autoCancelTaxiOrderDTO = taxiCancelOrderTDao.getPushCancelTaxiOrderInfo(taxiOrdert.getPlaceOrderUserId());
					
					if(autoCancelTaxiOrderDTO != null){
						
						// 订单Id
						autoCancelTaxiOrderDTO.setOid(taxiOrdert.getTaxiOrdertId());
						// 订单状态
						autoCancelTaxiOrderDTO.setOrderStatus(TaxiOrderStatus.ORDER_STATUS_CANCEL);
						// 订单类型
						autoCancelTaxiOrderDTO.setPublishType(2);
						
						// 自动取消出租车订单 - 发送短信
						this.sendTaxiMessage(autoCancelTaxiOrderDTO);
						
						// 自动取消出租车订单 - 推送消息
						this.pushTaxiMessage(autoCancelTaxiOrderDTO);
						
						// 自动取消出租车订单 - 通知推送消息
						this.pushTaxiNoticeMessage(autoCancelTaxiOrderDTO);
					}
					
				}
			}
		}
	}
	
	/**
	 * 
	 * 取消订单发送短信
	 * 
	 * @Title: sendMessage 
	 * @param pushCancelOrderDTO 
	 * @author YHQ
	 * 
	 */
	public void sendTaxiMessage(PushAutoCancelTaxiOrderDTO autoCancelTaxiOrderDTO){

		MessageRequestsDTO messageRequestsDTO = new MessageRequestsDTO();
		messageRequestsDTO.setTelPhone(autoCancelTaxiOrderDTO.getTellPhone());
		messageRequestsDTO.setMessageContent(MessageModel.AUTO_CANCEL_ORDER_INFO);
		queuefacade.addMessageToQueue(JSONUtil.toJSONString(messageRequestsDTO));

	}

	/**
	 *  取消订单推送消息
	 * 
	 * @Title: pushMessage 
	 * @param pushCancelOrderDTO    设定文件 
	 * @author YHQ
	 * 
	 */
	public void pushTaxiMessage(PushAutoCancelTaxiOrderDTO autoCancelTaxiOrderDTO) {

		// 推送Bean
		PushData pushData = new PushData();

		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular("cancelOrderPush");

		// 推送内容
		pushData.setResponseBody(autoCancelTaxiOrderDTO);

		PushRequestDTO pushRequestDTO = new PushRequestDTO();
		pushRequestDTO.setAlert(PushMsg.CANCEL_ORDER);
		pushRequestDTO.setAliasId(autoCancelTaxiOrderDTO.getAliasId());
		pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));
		pushRequestDTO.setPushType(PushType.alert_msgcontent);
		// 设备类型
		if ("Android".equals(autoCancelTaxiOrderDTO.getLoginEquipment())) {
			pushRequestDTO.setClientType(ClientType.Android);
		} else if (autoCancelTaxiOrderDTO.getLoginEquipment().equals("iOS")) {
			pushRequestDTO.setClientType(ClientType.iOS);
		}

		queuefacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));

	}
	
	/**
	 *  取消订单-通知推送消息
	 * 
	 * @Title: pushTaxiNoticeMessage 
	 * @param pushCancelOrderDTO    设定文件 
	 * @author YHQ
	 * 
	 */
	public void pushTaxiNoticeMessage(PushAutoCancelTaxiOrderDTO autoCancelTaxiOrderDTO) {
		
		// 推送Bean
		PushData pushData = new PushData();
		
		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular("newsNoticePush");
		
		// 推送内容
		pushData.setResponseBody(PushModel.noticeModel(1, MessageModel.AUTO_CANCEL_ORDER_INFO, null));
		
		PushRequestDTO pushRequestDTO = new PushRequestDTO();
		pushRequestDTO.setAlert(PushMsg.CANCEL_ORDER);
		pushRequestDTO.setAliasId(autoCancelTaxiOrderDTO.getAliasId());
		pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));
		pushRequestDTO.setPushType(PushType.msgcontent);
		// 设备类型
		if ("Android".equals(autoCancelTaxiOrderDTO.getLoginEquipment())) {
			pushRequestDTO.setClientType(ClientType.Android);
		} else if (autoCancelTaxiOrderDTO.getLoginEquipment().equals("iOS")) {
			pushRequestDTO.setClientType(ClientType.iOS);
		}
		
		queuefacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));
		
	}

}
